<template lang="pug">
  section
    .pageModel
      header.pageModel-header
        AutoComplete(v-model='testUrlAddress',placeholder='测试URL地址',style="width:500px;margin-right: 10px;",@on-focus='handleGetHistory')
          Option(v-for="(option, index) in historyData",:value="option.title",:key="index")
            span {{option.title}}
            Icon(type='md-trash',@click.stop='handleDeleteHistory(option,index)')
        Select(v-model='betaLabel',style='width:150px')
          Option(v-for="(item, index) in betaData",:value='item.value',:key="index") {{item.label}}
        Button(type='primary',:loading="loading",style='margin-left:10px',@click.stop='handleBeta') 测试
        span(style='display: inline-block;line-height: 32px;margin-left: 8px;color: #1890ff;') {{testStatusText}}
      section.pageModel-body
        .pageModel-body_con(v-if="pageModelItems.length!==0")
          pageModelItem(v-for="(item, index) in pageModelItems",:item='item',:httpCon='extractTypeLists',@removeItem='handleDeleteItem(index)',:key="index")
        .pageModel-body_json(v-if="attrSetData!==''||extUrlsData!==''||pageTurningUrlsData!==''")
          div(v-if="attrSetData!==''",)
            span data：
            vue-json-pretty(:data='attrSetData',:deep='2',showLength)
          div(v-if="extUrlsData!==''",)
            span extUrls：
            vue-json-pretty(:data='extUrlsData',:deep='2',showLength)
          div(v-if="pageTurningUrlsData!==''",)
            span pageTurningUrls：
            vue-json-pretty(:data='pageTurningUrlsData',:deep='2',showLength)
          Spin(v-if="true",fix,size="large")
      Button(type='dashed',icon='plus',@click='handleAddAttr',style='width: 500px;') 添加属性或属性组

    Modal(title='属性/属性组',v-model='attributeModal',@on-cancel='handleCancel',transfer)
      Form(ref='attributeForm',:model='formValidate',:rules='ruleValidate',:label-width='80')
        FormItem(label=' ', prop='radio')
          RadioGroup(v-model='formValidate.radio')
            Radio(v-for='(type,index) in groupTypeData',:label='type.id',:key='index') {{type.name}}
        FormItem(label='属性组：', prop='par')
          Select(v-model='formValidate.par')
            Option(v-for='(option,index) in optionData',:value='option.propertyId',:key='index') {{option.propertyName}}
        FormItem(label='名称：', prop='name')
          Input(v-model='formValidate.name')
      template(slot='footer')
        Button(@click='handleCancel') 取消
        Button(type='primary', @click="handleSubmit") 确定
</template>

<script>
import { uuid } from '@/utils/utils'
import VueJsonPretty from 'vue-json-pretty'
import pageModelItem from './pageModelItem'
import { asyncMould } from '../../api'
export default {
  components: { pageModelItem, VueJsonPretty },
  props: {
    extractTypeLists: { type: Array },
    testStatusText: { type: String }
  },
  data() {
    return {
      attrSetData: '',
      extUrlsData: '',
      pageTurningUrlsData: '',
      loading: false,
      historyData: [],
      showHistory: false,
      betaData: [
        { value: 0, label: '普通页面模型验证' },
        { value: 1, label: '社保页面模型验证' },
        { value: 2, label: '普通页面清洗验证' },
        { value: 3, label: '社保页面清洗验证' }
      ],
      betaLabel: 0,
      testUrlAddress: '',
      pageModelItems: [],
      attributeModal: false,
      groupTypeData: [{ id: 0, name: '属性' }, { id: 1, name: '属性组' }],
      optionData: [{ propertyId: '-1', propertyName: '顶级' }],
      formValidate: {
        radio: 0,
        par: '-1',
        name: ''
      },
      ruleValidate: {
        par: [{ required: true, message: '请选择属性组', trigger: 'change' }],
        name: [{ required: true, message: '请输入属性/属性组名称', trigger: 'blur' }]
      }
    }
  },
  watch: {
    attributeModal() {
      this.$refs.attributeForm.resetFields()
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$route.name === 'mould_setting') {
        document.addEventListener('click', e => {
          if (!this.$el.contains(e.target)) {
            this.showHistory = false
          }
        })
      }
    })
  },
  methods: {
    handleBeta() {
      this.loading = true
      this.$emit('handleModelBeta')
    },
    handleGetHistory: async function() {
      if (this.$route.query.modelId) {
        this.historyData = []
        try {
          const res = (await asyncMould.getVerifyUrls({ params: { modelId: this.$route.query.modelId } })).data.data
          res.forEach(item => this.historyData.push({ title: item }))
        } catch (error) {}
      }
    },
    handleDeleteHistory: async function(verifyUrl, index) {
      try {
        await asyncMould.deleteVerifyUrl({ params: { modelId: this.$route.query.modelId, verifyUrl: verifyUrl.title } })
        this.historyData.splice(index, 1)
      } catch (error) {}
    },
    handleAddAttr() {
      this.attributeModal = true
      this.handleChangeOptionData(this.pageModelItems)
    },
    handleCancel() {
      this.attributeModal = false
    },
    handleDeleteItem(index) {
      this.pageModelItems.splice(index, 1)
    },
    handleSubmit() {
      this.$refs['attributeForm'].validate(valid => {
        if (valid) {
          let obj = {
            parentId: 0,
            propertyId: uuid(),
            modelId: this.$route.query.modelId,
            propertyName: this.formValidate.name,
            urlPropertyExtract: 0,
            parseType: 1,
            matchExpression: '',
            jsonPath: '',
            regex: '',
            groupType: this.formValidate.radio
          }
          if (this.formValidate.radio !== 0) obj.children = []
          if (this.formValidate.par === '-1') {
            this.pageModelItems.push(obj)
          } else {
            this.handleFormatData(this.pageModelItems, this.formValidate.par, obj)
          }
          this.attributeModal = false
        }
      })
    },
    handleFormatData(data, par, item) {
      /**
       * @description 表单提交时数据构建
       */
      for (let i in data) {
        if (data[i].propertyId === par) {
          item.parentId = par
          data[i].children.push(item)
          break
        } else {
          if (this.handleFormatData(data[i].children, par, item)) {
            item.parentId = par
            data[i].children.push(item)
            break
          }
        }
      }
    },
    handleFormatQueryData(formatData) {
      /**
       * @description 回显数据格式化
       */
      formatData.forEach(item => {
        if (item.groupType === 1) item.children = []
        formatData.forEach(ele => {
          if (item.propertyId === ele.parentId) item.children.push(ele)
        })
      })
      for (var i = formatData.length - 1; i >= 0; i--) {
        if (formatData[i].parentId !== '0') formatData.splice(i, 1)
      }
      this.rebuildPropertyId(formatData)
      this.pageModelItems = formatData
      this.handleChangeOptionData(formatData)
    },
    rebuildPropertyId(data) {
      data.forEach(item => {
        item.propertyId = uuid()
        if (item.children) {
          item.children.forEach(child => {
            child.parentId = item.propertyId
            this.rebuildPropertyId(item.children)
          })
        }
      })
      return data
    },
    handleChangeOptionData(optionData) {
      this.optionData = [{ propertyId: '-1', propertyName: '顶级' }]
      const filterOptionData = optionData => {
        optionData.forEach(item => {
          if (item.groupType === 1) this.optionData.push({ propertyId: item.propertyId, propertyName: item.propertyName })
          if (item.children) filterOptionData(item.children)
        })
      }
      filterOptionData(optionData)
    }
  }
}
</script>

